/*
 * Copyright (c) 2006, 2022, webrx.cn All rights reserved.
 *
 */
package cn.webrx.serviet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Random;

/**
 * <p>Project: javaweb - T2
 * <p>Powered by webrx On 2022-03-15 09:34:08
 * <p>Created by IntelliJ IDEA
 *
 * @author webrx [webrx@126.com]
 * @version 1.0
 * @since 17
 */
@WebServlet(urlPatterns = {"/api/t2"})
public class T2 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println(req.getParameter("id"));
        System.out.println(req.getParameter("name"));
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        PrintWriter out = resp.getWriter();
        out.printf("欢迎：%s，你的数据已经保存完成。", req.getParameter("name"));
        out.flush();
        out.close();
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        System.out.println(req.getParameter("id"));
        System.out.println(req.getParameter("name"));
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        PrintWriter out = resp.getWriter();
        String json = "{\"code\":200,\"msg\":\"save success\"}";

        String action = req.getParameter("action");
        if (action == null) {
            out.print(json);
        } else if ("save".equals(action)) {
            String a = req.getParameter("a");
            String p = req.getParameter("p");
            json = String.format("{\"code\":200,\"msg\":\"%s保存完成.\"}",a);
            out.print(json);
        }else if("check".equals(action)){
            System.out.println("check..................................................");
            String a = req.getParameter("a");
            System.out.println(a);
            Random rand = new Random();
            if(rand.nextBoolean()){
                json = String.format("{\"code\":201,\"msg\":\"%s恭喜，可以注册.\"}",a);
            }else{
                json = String.format("{\"code\":202,\"msg\":\"%s此账号已经.\"}",a);
            }
            out.print(json);
        }
        out.flush();
        out.close();
    }
}
